<!-- 生长繁育 界面 -->

<template>
	
	<!-- 顶部卡片-->
	<view >
		<uni-card title="生长繁育"  sub-title="D8602032700"  extra="额外信息" :thumbnail="avatar">
			<view class="modechooose">
				<text class="uni-body">未激活</text>
				<text class="uni-body">影子模式</text>
			</view>
		</uni-card>
	</view>
	
	<!-- 生长繁育相关数据 -->
	<view class="datalang">
		<uni-segmented-control :current="current" :values="itemsturang" @clickItem="onClickItem" styleType="text" activeColor="#4cd964">
		</uni-segmented-control>
		        <view class="content">
					<view v-if="current === 0">
					    <view>
					        <uni-card :is-shadow="false">
					             <view class="uni-list-cell uni-list-cell-pd">
					                <view class="uni-list-cell-db">您有新的预警消息待查收！</view>
					            </view>
					        </uni-card>
					        <view class="cu-timeline">
					            <template v-for="(item, index) in warningMessages" :key="index">
					                <view v-if="item.date" class="cu-time" style="white-space: nowrap; padding: 5px;">{{ item.date }}</view>
					                <view class="cu-item" :class="item.type">
					                    <view class="shadow-blur content">
					                        <view class="cu-item">
					                            <view class="content">
					                                <view class="cu-capsule radius">
					                                    <view :class="['cu-tag', item.type === 'warning' ? 'bg-red' : 'bg-green']">{{ item.time.period }}</view>
					                                    <view :class="['cu-tag', item.type === 'warning' ? 'line-red' : 'line-green']">{{ item.time.hour }}</view>
					                                </view>
					                            </view>
					                            <view class="margin-top">
					                                <text style="font-size: 25rpx;">{{ item.message }}</text>
					                            </view>
												<view class="cu-item-image">
												    <image :src="item.image" class="img-size" mode="aspectFill"></image>
												</view>
					                        </view>
					                    </view>
					                </view>
					            </template>
					        </view>
					    </view>
					</view>
					
		            <view v-if="current === 1">
		                <view>
							<uni-card :is-shadow="false" >
								<view class="uni-list-cell uni-list-cell-pd">
									<view class="uni-list-cell-db">是否开启实时数据</view>
									<switch checked />
								</view>
							</uni-card>
							
							<!-- 数据采集内容 -->
							        <view class="data-list">
							            <template v-for="(item, index) in growthDataList" :key="index">
							                <view class="data-item">
							                    <view class="data-item-header">
							                        <view class="data-item-time">
							                            <view class="cu-capsule radius">
							                                <view class="cu-tag bg-cyan">{{ item.time.period }}</view>
							                                <view class="cu-tag line-cyan">{{ item.time.hour }}</view>
							                            </view>
							                        </view>
													<view class="data-item-date">
														{{ item.date }}
													</view>
							                    </view>
							                    <view class="data-item-image">
							                        <image :src="item.image" class="img-size" mode="aspectFill"></image>
							                    </view>
							                </view>
							            </template>
							        </view>
							
						</view>
		            </view>
					
		            <view v-if="current === 2">
		                设备控制
		            </view>
					
		            <view v-if="current === 3">
		                设备日志
		            </view>
					
					<view v-if="current === 4">
						<view class="charts-box">
						    <qiun-data-charts 
						      type="line"
						      :opts="optsGrowthWeekData"
						      :chartData="chartDataGrowthWeekData"
						    />
						</view>
						<view class="charts-box">
						    <qiun-data-charts 
						      type="line"
						      :opts="optsGrowthMonthData"
						      :chartData="chartDataGrowthMonthData"
						    />
						</view>
					</view>
					
		        </view>
					
	</view>
	
	
</template>

<script setup>
import { ref, onMounted } from "vue"
import { API_BASE_URL } from "/env_config.js"
import request from '/utils/request';
import { getDeviceListByHouseID } from "@/api/duorou/dapengDeviceBind";
import { getAllGrowthDataList, getGrowthDataByWeek, getGrowthDataByMonth } from "@/api/duorou/growReproduce";

const baseUrl=API_BASE_URL ;
const avatar = ref("../../../../static/images/growth.png");
//分段器
const itemsturang = ref(['预警消息','数据采集', '设备控制', '设备日志','数据分析'])
const current =ref(0)
function onClickItem(e){
	if (current.value != e.currentIndex) {
	        current.value = e.currentIndex;
			getGrowthPageData(current.value)
	}
}

function getGrowthPageData(current) {
    if (current === 3) {
        getGrowthWeekData();
        getGrowthMonthData();
    }
}


//判断出现病虫害的时间是上午、下午还是晚上
function getPeriod(hour) {
  const hourInt = parseInt(hour, 10);
  if (hourInt >= 0 && hourInt < 12) {
    return "上午";
  } else if (hourInt >= 12 && hourInt < 18) {
    return "下午";
  } else {
    return "晚上";
  }
}

const getMessageImageUrl = (message) => {
    const params = message.messageSpecialInfo
      .replace(/\{|}/g, '')
      .split(', ')
      .reduce((acc, item) => {
            const [key, value] = item.split('=');
            acc[key] = value;
            return acc;
        }, {});

    // 检查 params.url 是否存在且不为空
    if (!params.url) {
        return "图片加载失败";
    }

    return params.url;
};

// 预警消息内容
const warningMessages = ref([]);

/**
 * 获取预警消息
 */
async function getWarningMessages() {
  try {
    const res = await request({
      url: '/admin/iotDeviceMessage/page',
      method: 'GET',
      data: {
        current: 1,
        size: 10
      }
    });
    if (res.statusCode === 200) {
      const records = res.data.data.records;
      const filteredRecords = records.filter(item => item.messageType === 'BEST_ALARM');
      const formattedMessages = filteredRecords.map(item => {
        const [date, time] = item.createTime.split(' ');
        const [year, month, day] = date.split('-');
        const [hour, minute] = time.split(':');
        const period = getPeriod(hour);
        return {
		  fullTime: `${year}-${month}-${day} ${hour}:${minute}`,
          date: `${year}-${month}-${day}`,
          time: { period, hour: `${hour}:${minute}` },
          type: 'normal',
          message: item.messageDescribe,
		  image: baseUrl+ getMessageImageUrl(item) ,
        };
      });
	  
	  // 新增排序逻辑（时间倒序）
	  formattedMessages.sort((a, b) => {
        return new Date(b.fullTime) - new Date(a.fullTime); // 降序排列
	  });
	  
      warningMessages.value = formattedMessages;
	  console.log('返回的消息：', warningMessages)
    } else {
      console.error('请求失败:', res.errMsg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
}

//设备信息
const iotDevice=ref(null) 

/**
 * 数据采集中的内容
 */
const growthDataList = ref([]);
// 获取所有生长繁育数据
async function getAllGrowthMeasureData() {
  try {
    const res = await getAllGrowthDataList({
      current: 1,
      size: 10,
    });
    if (res.statusCode === 200) {
      growthDataList.value = res.data.data.records.map((item) => {
        const [date, time] = item.updateTime.split(" ");
        const [year, month, day] = date.split("-");
        const [hour, minute] = time.split(":");
        const period = getPeriod(hour);
        return {
          date: `${year}-${month}-${day}`,
          time: { period, hour: `${hour}:${minute}` },
          image: baseUrl + item.detectedFileName,
        };
      });
    } else {
      console.error("请求失败:", res.errMsg);
    }
  } catch (error) {
    console.error("请求出错:", error);
  }
}

//数据分析的图
//生长繁育统计--周
const chartDataGrowthWeekData = ref({})
const optsGrowthWeekData = ref({
	color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
	        padding: [15,10,0,15],
	        enableScroll: false,
	        legend: {},
	        xAxis: {
	          disableGrid: true
	        },
	        yAxis: {
	          gridType: "dash",
	          dashLength: 2
	        },
	        extra: {
	          line: {
	            type: "straight",
	            width: 2,
	            activeType: "hollow"
	          }
	        }
})
function getGrowthWeekData(){
	setTimeout(() => {
	        //模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
	        let res = {
	            categories: ["12-18","12-19","12-20","12-21","12-22","12-23","12-24"],
	            series: [
	              {
	                name: "检测植株数--周",
	                data: [35,28,25,37,24,20,43]
	              }
	            ]
	          };
	        chartDataGrowthWeekData.value = JSON.parse(JSON.stringify(res));
	      }, 500);
}

//生长繁育统计--月
const chartDataGrowthMonthData = ref({})
const optsGrowthMonthData = ref({
	color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
	        padding: [15,10,0,15],
	        enableScroll: false,
	        legend: {},
	        xAxis: {
	          disableGrid: true
	        },
	        yAxis: {
	          gridType: "dash",
	          dashLength: 2
	        },
	        extra: {
	          line: {
	            type: "straight",
	            width: 2,
	            activeType: "hollow"
	          }
	        }
})
function getGrowthMonthData(){
	setTimeout(() => {
	        //模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
	        let res = {
	            categories: ["6月","7月","8月","9月","10月","11月","12月"],
	            series: [
	              {
	                name: "检测植株数--月",
	                data: [0,0,0,121,768,823,845]
	              }
	            ]
	          };
	        chartDataGrowthMonthData.value = JSON.parse(JSON.stringify(res));
	      }, 500);
}

onMounted(() => {
  getWarningMessages();
  getAllGrowthMeasureData();
});
</script>

<style lang="scss">
.uni-card {
		.uni-card__header{
			margin-top: 20rpx;
			.uni-card__header-content{
				margin-left: 20rpx;
			}
		}
	}
	.modechooose{
		display: flex;
		flex-direction: row;
		font-size: 13px;
		margin-left: 70rpx;
		.uni-body{
			margin-left: 30rpx;
		}
		
	}
	.datalang{
		margin-top: 30rpx;
	}
	.uni-list-cell {
		position: relative;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		
		.uni-list-cell-pd {
			padding: 22rpx 30rpx;
		}
		.uni-list-cell-db {
			margin-left: 20rpx;
			flex: 1;
		}
	}
	.datadetail{
		display: flex;
		flex-direction: row;
		.datadetail-small{
			display: flex;
			flex-direction: row;
			.uni-body1{
				// margin-left: 10rpx;
			}
			.uni-body2{
				display: flex;
				margin-left: auto;
			}
		}
	}
	
	.charts-box {
	    width: 100%;
	    height:  500rpx;
		margin-top: 15rpx;
	}
	
	.img-size{
		height: 300rpx;
	}

.cu-timeline {
	margin-left: 20rpx;
	margin-right: 20rpx;
	border-radius: 5rpx;
}

.cu-item-image {
	width: 100%;
	height: 300rpx;
	border-radius: 10rpx;
	overflow: hidden;
	margin-top: 20rpx;
}

.data-list {
    padding: 20rpx;
}

.data-item {
    background-color: #fff;
    border-radius: 10rpx;
    box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
    padding: 30rpx;
    margin: 0 5rpx 40rpx 5rpx;
}

.data-item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
}

.data-item-date {
    font-size: 14px;
    color: #666;
}

.data-item-time {
    display: flex;
    align-items: center;
    gap: 10rpx;
}

.data-item-image {
    width: 100%;
    height: 400rpx;
    border-radius: 10rpx;
    overflow: hidden;
    margin-top: 20rpx;
}

.img-size {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

</style>
